<template>
    <base-modal
      :title="title"
      width="680px"
      :show.sync="visible"
      :mask-closeable="false"
    >
    <div class="form-content">
     <el-form ref="ruleform" :model="form" label-width="80px" :rules="rules" v-loading="formloading">
      <el-form-item :label="$t('common.base.rulerName')" prop="ruleName">
        <el-input v-model="form.ruleName" :placeholder="$t('product.setting.qrCodeSet.rulers.des1')" maxlength="20" show-word-limit></el-input>
      </el-form-item>
      <el-form-item :label="$t('projectManage.setting.messageSetting.label1')" prop="triggerTarget" >
        <el-radio-group v-model="form.triggerTarget" @change="handleObjType">
          <el-radio label="PROJECT">{{$t('projectManage.setting.messageSetting.option1')}}</el-radio>
          <el-radio label="TASK">{{$t('projectManage.setting.messageSetting.option2')}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <template v-if="form.triggerTarget == 'TASK'">
        <el-form-item :label="$t('common.fields.taskName.displayName')" prop="taskId">
          <el-select v-model="form.taskId" style="width: 100%;" @change="taskTypeChange">
            <el-option
              v-for="item in taskList"
              :key="item.id"
              :label="item.projectTaskName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </template>

      <el-form-item :label="$t('projectManage.setting.messageSetting.label4')" prop="triggerTimeType" >
        <el-radio-group v-model="form.triggerTimeType" @change="resetTime(1)">
          <el-radio label="FIXED_TIME">{{$t('projectManage.setting.messageSetting.option4')}}</el-radio>
          <el-radio label="REAL_TIME">{{$t('projectManage.setting.messageSetting.option5')}}</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 定时触发 -->
      <template v-if="form.triggerTimeType === 'FIXED_TIME'">
        <el-form-item :label="$t('projectManage.setting.messageSetting.label2')" prop="timeName">
          <div class="time-wrap">
            <el-select v-model="form.timeName" style="width: 23%" @change="timeFieldChange">
              <el-option
                v-for="item in timeTypeList"
                :key="item.fieldName"
                :label="item.displayName"
                :value="item.fieldName"
              >
              </el-option>
            </el-select>
            <el-select v-model="form.moment" style="width: 23%">
              <el-option :label="$t('common.base.before')" value="before">{{ $t('common.base.before') }}</el-option>
              <el-option :label="$t('common.base.after')" value="after">{{ $t('common.base.after') }}</el-option>
            </el-select>
            <!-- 支持0天 -->
            <el-input-number style="width: 23%" v-model="form.timeNum" @blur="timeNumBlur" :precision="0" controls-position="right" :min="0" :max="999"></el-input-number>
            <el-select style="width: 23%" v-model="form.timeType">
              <el-option :label="$t('common.base.abbrDay')"  value="day">{{ $t('common.base.abbrDay') }}</el-option>
              <el-option :label="$t('common.base.week')"  value="week">{{ $t('common.base.week') }}</el-option>
              <el-option :label="$t('common.base.month')"  value="month">{{ $t('common.base.month') }}</el-option>
            </el-select>
          </div>
        </el-form-item>
      </template>

      <!-- 实时触发 -->
      <template v-if="form.triggerTimeType === 'REAL_TIME'">
        <el-form-item :label="$t('projectManage.setting.messageSetting.label5')" prop="triggerAction" >
          <el-select v-model="form.triggerAction">
            <el-option
              v-for="item in nodeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </template>

      <el-form-item :label="$t('projectManage.setting.messageSetting.label3')" prop="triggerRuleForm">
        <div class="condition-wrap" v-loading="conditionloading">
          <ConnectorModuleRuleForm
            v-if="showForm"
            isSelect
            :toFieldList="toFieldList"
            :value="form.triggerRuleForm"
            :fromFieldList="fromFieldList"
            :fromBizTypeName='fromBizTypeName'
            :toBizTypeName='toBizTypeName'
            @input="onConnectorSelectRuleFormInputHandler"
            justFixedValue
            :showHeader="false"
          />
          <!-- 最多可创建10个条件 -->
          <el-button type="primary" v-if="form.triggerRuleForm.length < 10" plain @click="addRuleFormItem"> + {{$t('common.base.add2')}}</el-button>
        </div>
      </el-form-item>

     </el-form>
    </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="submitRule">{{$t('common.base.save')}}</el-button>
      </div>
    </base-modal>
</template>
<script>

import * as triggerApi from '@src/modules/connector/api/trigger';
import {
  taskItemDetail,
  getProjectTypeField, 
  taskList, 
  addMessageRule,
  updateMessageRule,
  messageRuleDetail,
  getStatusList } from '@src/api/ProjectManage.ts';
import{  getAllFields } from '@src/api/TaskApi';
import { getFormFieldListInfo } from '@src/api/PassApi'

import { ConnectorModuleRuleForm } from '@src/modules/connector/components'
import { connectorFromFieldsAddChildren } from '@src/modules/connector/util';
import { createConnectorRuleFormItem } from '@src/modules/connector/util'
import { connectorRuleFormToConnectorOptionsFieldOption, ConnectorOptionsFieldOptionToConnectorRuleForm} from '@src/modules/connector/util/card';
import { t } from '@src/locales'
import _ from 'lodash'
import { projectStatusField, taskStatusField} from './projectFixData'


export default {
  name: 'project-message-rule',
  data() {
    return {
      title: '',
      visible: false,
      form: {
        ruleName: '',
        timeName: '',
        timeNum: 0,
        moment: 'before',
        timeType: 'day',
        triggerTarget: 'PROJECT',
        triggerRuleForm: [],
        triggerType: '', // 可选的任务 ALL 全部任务 SINGLE 单个任务
        projectTaskConfigId: '',  
        projectTaskConfigName: '',  
        triggerDateRule:  '',  // 
        triggerTimeType: 'FIXED_TIME',
        triggerAction: 'STATUS_CHANAGE',
      },
      timeTypeName: '', // 当前日期时间的中文名，用于列表展示
      showForm: false, // 初始化触发器表单
      rules: {
        ruleName: [
          { required: true, message: t('product.setting.qrCodeSet.rulers.des1'), trigger: 'blur' },
        ],
        timeName: [
          { required: true, message: t('common.base.pleaseSelect'), trigger: 'change',  },
        ],
        triggerRuleForm: [
          { required: true, message: t('projectManage.setting.messageSetting.tip3'), trigger: 'change',  },
        ]
      },
      // 触发节点
      nodeOptions: [
        {
          value: 'STATUS_CHANAGE',
          label: t('projectManage.setting.messageSetting.option6')
        },
      ],
      taskList: [],
      projectTypeField: [], // 所有的项目类型表单字段

      timeTypeList: [], //  当前表单所有时间控件的字段
      projectTimeField:[], // 项目表单的时间字段
      taskTimeField:  [], // 任务表单的时间字段

      fromFieldList:[],
      toFieldList: [],
      projectStatusField,
      taskStatusField,
      fromBizTypeName: '',
      toBizTypeName: '',
      taskFormId: '', // 工单类型表单的id
      isEditStatus: false, // 是否是编辑状态
      conditionloading: false,
      formloading: false, // 整个表单加载
    }
  },
  props: {
    projectTypeId: {
      type: String,
      default: ''
    }
  },
  components: {
    ConnectorModuleRuleForm
  },
  computed: {
    isShowCondition(){
      // 选择触发对象是任务的时候，并且选择全部任务的时候，不显示触发条件
      return !(this.form.triggerTarget === 'TASK' && !this.form.taskId)
    },
   },
  methods: {
    async submitRule() {
      this.$refs['ruleform'].validate((valid, object) => {
        if (valid) {

          let params = {}
          if (this.form.triggerTarget === 'PROJECT') {
            // 项目规则
            delete this.form.projectTaskConfigId
            delete this.form.projectTaskConfigName
            delete this.form.triggerType
          } else {
            // 任务规则 全部任务SINGLE  单个任务 SINGLE
            this.form.triggerType  = this.isShowCondition ?  'SINGLE' :  'ALL'
          }

    
          // 判断触发条件是否都必填 
          if (!this.form.triggerRuleForm?.length)  {
            // 触发条件必填
            this.$message.error(t('projectManage.setting.messageSetting.tip2'))
          } else {
            let isAllValidate = this.checkRule()
            if (!isAllValidate) return this.$message.error(t('projectManage.setting.messageSetting.tip2'))
          }

          let conditionList = _.cloneDeep(this.form.triggerRuleForm)
          let conditionParams = (conditionList || []).map(item => {
              // 新建的话false 不然会影响到数据为数组和对象的处理
              // 编辑的话就是true
              return connectorRuleFormToConnectorOptionsFieldOption(item, true);
          })

          let conditionParamsArr = [] // 兼容触发器双数组
          if (conditionParams?.length) {
            conditionParamsArr[0] = conditionParams.map((item) => {
              return {
                ...item,
                moduleType: this.form.triggerTarget === 'PROJECT' ? 'project': 'projectTask'
              }
            })
          }

          // 判断是否触发日期的字段都填写完整
          // 判断触发时间 定时/实时
          if (this.form.triggerTimeType === 'FIXED_TIME') {
            // 定时时间
            if (this.form.timeName) {
            // 如果触发日期存在的话
              params.triggerDateRule = {
                timeName: this.form.timeName,
                moment: this.form.moment,
                timeNum: this.form.timeNum || 0,
                timeType: this.form.timeType,
                // 触发日期拼接的所有中文
                timeTypeAllName: this.allNameFun(),
              }
            }
          }
      
          params = {
            ...this.form,
            ...params,
            triggerRule: conditionParamsArr,
            projectTypeId: this.projectTypeId,
          }

          // 实时触发的话，删除掉触发日期
          if (params.triggerTimeType === 'REAL_TIME') {
            delete params.triggerDateRule
          }

          if (this.isEditStatus) {
            // 更新规则
            updateMessageRule(params).then((res) => {
              this.resultMess(res)
            })

          } else {
            // 新建规则
            addMessageRule(params).then((res) => {
              this.resultMess(res)
            })
          }
         }
      })
    },

    
    timeNumBlur(event) {
      if (!event.target.value) {
        // 默认是0
        this.$set(this.form, 'timeNum', 0)
      }
    },

    // 接口报错统一处理
    resultMess(res) {
      if (!res.success) return this.$message.error(res.message)
      this.$message.success(t('common.base.tip.operationSuccess'))
      this.visible = false
      // 更新表格的数据
      this.$emit('getListByModule')
    },

    allNameFun() {
      let momentName = this.form.moment ===  'before' ? t('common.base.before') : t('common.base.after')

      let timeTypeObj = {
        'day':  t('common.base.abbrDay'),
        'week': t('common.base.week'),
        'month': t('common.base.month'),
      }
      return `${this.timeTypeName}${momentName}${this.form.timeNum || 0}${timeTypeObj[this.form.timeType]}`
    },

    // 触发日期时间字段改变
    timeFieldChange(fieldName) {
      if (!fieldName) return
      this.timeTypeName = this.timeTypeList.filter((item) => item.fieldName === fieldName)[0]?.displayName || ''
    },

    // 检查规则是否为空
    checkRule() {
      let ruleArr = this.form.triggerRuleForm
      return ruleArr.every((item)  => Array.isArray(item.value) ? (item.value.length > 0) : item.value )
    },

    /**
     * @description 用户名样式重叠补丁
     */
     userNameStyleOverlapPolyfill() {
      
      const userInputList = (this.$el.querySelectorAll('.user-search input') || [])
      
      userInputList.forEach(userInputElement => {
        if (userInputElement.value) {
          userInputElement.value = ''
          userInputElement.placeholder = ''
        }
      })
      
    },

    addRuleFormItem() {
      this.form.triggerRuleForm = [...this.form.triggerRuleForm, createConnectorRuleFormItem()];
    },
    onConnectorSelectRuleFormInputHandler(val) {
      // 添加子属性
      connectorFromFieldsAddChildren(this.fromFieldList);
      this.form.triggerRuleForm = val;
    },
    async openDialog(row) {
      this.visible = true
      this.formloading = true
      this.$refs['ruleform'].resetFields();

      if (row) {
        // 编辑规则
        await messageRuleDetail({id:row.id}).then( async(res) => {
          const { success, message, data } = res
          if (!success ) return this.$message.error(message)
          // 当前任务列表的id
          if (data?.triggerDateRule) {
            const { timeName, timeNum, moment, timeType, } = data.triggerDateRule
            data.timeName = timeName || ''
            data.timeNum = timeNum || ''
            data.moment = moment || ''
            data.timeType = timeType || ''
          }

          if (data.triggerRule && data.triggerRule.length) {
            data.triggerRuleForm = [...data.triggerRule[0]]
          }

          data.taskId = data?.projectTaskConfigId || ''
          this.$set(this, 'form',  _.cloneDeep(data))
          this.title = t('common.base.editRule')

          if (this.form.triggerTarget == 'TASK') {
            // 获取任务类型列表
            await this.getTaskTypeList()
          }

          if (this.form.triggerTarget === 'TASK') {
            // 通过任务id 获取当前任务表单的字段
            this.taskTypeChange(this.form.taskId, 'edit')
          } else {
            // 获取当前项目类型配置的表单字段
            await this.getProjectFormList()
          }

          // 编辑的时候回显中文
          this.timeFieldChange(this.form?.timeName)
          this.isEditStatus = true
        })
      } else {
        this.title = t('message.setting.cusMes.t5')
        await this.getProjectFormList()
        this.setDefaultVal()
        this.isEditStatus = false
      }

    },

    // 设置新增的默认值
    setDefaultVal() {
      // 重置页面的数据
      this.$set(this, 'form', {})
      this.$set(this.form, 'ruleName', '')
      this.$set(this.form, 'triggerTarget', 'PROJECT')
      this.$set(this.form, 'triggerTimeType', 'FIXED_TIME')
      this.$set(this.form, 'triggerAction', 'STATUS_CHANAGE', )
      this.$set(this.form, 'triggerRuleForm', [])
      this.$set(this.form, 'timeName', '')
      this.$set(this.form, 'moment', 'before')
      this.$set(this.form, 'timeNum', 0)
      this.$set(this.form, 'timeType', 'day')
    },

    // 这个要根据规则类型获取不同的 字段表单 项目/工单/任务
    async getToFieldList(type) {
      this.conditionloading = true
      // 触发器之前的接口
      let bizType = ''
      let bizTypeId = '0' // 全部任务类型/工单任务类型 固定传值

      if (type === 'PROJECT') {
        bizType = 'PROJECT_MANAGER'
        bizTypeId = this.projectTypeId
      } else if (type === 'WORK_TASK' || type === 'PAAS_TASK') {
        // 工单任务
        bizType = 'COMMON_TASK'
        // bizTypeId = '0'
      } else if (type === 'COMMON_TASK') {
        // 通用任务
        bizType = 'COMMON_TASK'
        bizTypeId = this.taskFormId || '0'  // 全部任务的话 默认0
      }

      // 全部任务和工单任务都取的是任务的系统模版字段
      await triggerApi.getTriggerConditionConfig({ bizTypeId: bizTypeId, bizType: bizType }).then( async res => {
        this.formloading = false
        this.conditionloading = false
        if (res.status == 0) {
            res.data.forEach((item) => {
              if (item.fieldType == 'date' || item.fieldType == 'datetime') {
                // 时间类型的只要介于判断符
                item.operateList = item.operateList.filter((ele) => (ele.enName === 'BETWEEN'))
              } else if (item.filedGroup !== 'system' && (item.fieldType == 'user' || item.fieldType == 'cascader')) {
                // 自定义字段的 多级菜单和人员只有等于操作符
                item.operateList = item.operateList.filter((ele) => (ele.enName === 'EQ'))
              } else {
                item.operateList = item.operateList.filter((ele) => (ele.enName === 'EQ' || ele.enName === 'NOT_EQ'))
              }
            })

           if (type === 'PROJECT') {
              this.toFieldList = [...this.projectStatusField, ...res.data || []]
           } else {
              this.toFieldList = [...this.taskStatusField,...res.data || []]
           }

          // 触发条件 过滤掉地址和位置
          this.toFieldList = this.toFieldList.filter((item) => item.fieldType !== 'address')

          // 获取当前项目类型的状态列表
          if (this.form.triggerTarget === 'PROJECT') {
            await this.getProjectStatus()
          }

          //  回显之前触发条件的数据
           if (this.toFieldList.length) {
              let conditionList = _.cloneDeep(this.form.triggerRuleForm)
              // 开始初始化触发条件 如果是空的话，默认会初始化一个
              let condition = (conditionList || []).map((item) => {
                return ConnectorOptionsFieldOptionToConnectorRuleForm(item, this.toFieldList, true )
              })
              this.$set(this.form, 'triggerRuleForm',  condition)
            this.showForm = true
          }
        }
        this.$nextTick(() => {
          this.userNameStyleOverlapPolyfill()
        })
      });
    },

    // 获取当前项目类型的状态
    async getProjectStatus() {
      await getStatusList({projectTypeId: this.projectTypeId}).then((res) => {
        if (res.success) {

          // 固定的已取消字段 id默认是0
          let cancelFix = [
            {
              id: 0, 
              projectStatusName: t('common.task.type.offed'),
            }
          ]
          
          // 所有的项目状态集合
          let allSource = [...res.data, ...cancelFix].map((item) => {
            return {
              value: item.id,
              text: item.projectStatusName
            }
          })

          // 项目状态的dataSource 单独赋值
          this.toFieldList.forEach(item => {
            if (item.enName === 'projectStatusId') {
              item.setting.dataSource = allSource
            }
          })
        }
      })
    },

    // 获取当前项目的所有表单字段
    async getProjectFormList() {
      let params = {
        tableName: 'project',
        templateId: this.projectTypeId
      }
      await getProjectTypeField(params).then( async(res) => {
        this.timeTypeList = []
        const { success, message, data } = res
        if (!success ) return this.$message.error(message)
        this.projectTypeField = data || []
        this.timeTypeList = this.getTimeField(data, 'project')
        await this.getToFieldList('PROJECT')
      })
    },

    // 获取时间类型的字段
    getTimeField(data, type) {
      let timeArr = []
      // 项目只取 'planStartTime', 'planEndTime', 'date'
      // 任务只取 planStartTime', 'planEndTime
      let timeAllType = ['planStartTime', 'planEndTime']
      let extendType = ['date']
      if (type === 'project') {
        timeAllType = [...timeAllType, ...extendType]
      }
      data.map((item) => {
        if (timeAllType.includes(item.formType)) {
          timeArr.push(item) 
        }
      })
      return timeArr
    },

    // 获取当前项目下的任务列表
    async getTaskTypeList() {
      await taskList({projectTypeId: this.projectTypeId}).then((res) => {
        const { success, message, data } = res
        if (!success ) return this.$message.error(message)
        if (data?.length) {
          data.unshift({
            projectTaskName: t('projectManage.setting.messageSetting.allOption'),
            id: '',
          })
          this.taskList = data
        }
      })
    },

    // 触发对象切换
    async handleObjType(item) {
      this.$set(this.form, 'taskId', '') // 之前的任务类型清除
      this.resetTime()
      this.resetRuleForm()
      
      if (item === 'TASK') {
        await this.getTaskTypeList()
        // 获取全部任务 通用任务系统字段
        this.getCommonField()
      } else {
        // 获取项目下的所有表单字段
        this.getProjectFormList()
      }
    },

    // 任务类型切换
    taskTypeChange(taskId, type) {
      // 清除之前选中的
      if (type !== 'edit') {
        // 编辑的时候，初次打开了弹窗
        this.resetTime()
        this.resetRuleForm()
      }
      let currentItem = this.taskList.filter((item) => item.id == taskId)[0]
      this.form.projectTaskConfigId = currentItem?.id
      this.form.projectTaskConfigName = currentItem?.projectTaskName
      this.taskFormId = currentItem?.taskFormId || ''

      if (currentItem && currentItem?.taskType === 'WORK_TASK' && currentItem?.taskFormId) {
        // 工单类型的任务 
        this.getWorkOderField(currentItem.taskFormId)
      }else if (currentItem && currentItem?.taskType === 'PAAS_TASK' && currentItem?.taskFormId) {
        // paas类型的任务
        this.getPassTaskField(currentItem)
      } else {
        // 通用类型的任务  
        this.getCommonField(currentItem?.taskFormId ||  '')
      }
    },

    // 获取通用任务的表单字段
    async getCommonField(taskFormId) {
      let params = {
        tableName: 'mission',
        templateId: taskFormId
      }
      await getProjectTypeField(params).then((res) => {
        this.timeTypeList = []
        const { success, message, data } = res
        if (!success ) return this.$message.error(message)
        this.timeTypeList = this.getTimeField(data, 'mission')
        this.getToFieldList('COMMON_TASK')
      })
    },

    // 获取工单任务的表单字段
    async getWorkOderField(taskFormId) {
      let params = {
        typeId: taskFormId,
        tableName: 'task',
        isFromSetting: true,
      }
      await getAllFields(params).then((res)  => {
        this.timeTypeList = []
      if (res && res.length) {
        this.timeTypeList = this.getTimeField(res, 'mission')
        this.getToFieldList('WORK_TASK')
      }
      })
    },

    // 获取PAA任务的表单字段
    async getPassTaskField(item) {
       try {
         this.timeTypeList = [
           {fieldName: 'planStartTime', displayName: this.$t('common.form.type.planStartTime')},
           {fieldName: 'planEndTime', displayName: this.$t('common.form.type.planEndTime')},
         ]
         this.getToFieldList('PAAS_TASK')
       } catch (e) {
         console.error(e)
       }
    },
    // 清除触发日期
    resetTime(type) {
      this.$set(this.form, 'timeName', '')
      this.$set(this.form, 'moment', 'before')
      this.$set(this.form, 'timeNum', 0)
      this.$set(this.form, 'timeType', 'day')
      this.$set(this.form, 'triggerAction', 'STATUS_CHANAGE', )
    },

    // 清除触发条件
    resetRuleForm() {
      // 清除当前的触发条件
      this.form.triggerRuleForm = ([]).map((item) => {
        return ConnectorOptionsFieldOptionToConnectorRuleForm(item, this.toFieldList, false )
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.form-content {
  padding: 20px 20px;
  margin: 0 auto;
}

.time-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .delete-icon  {
    padding: 0 6px;
  }
}
::v-deep .form-item-project {
    // height: 32px!important;
    .el-select {
      max-width: 160px!important;
    }
    .err-msg-wrap {
      display: none!important;
    }
    .el-date-editor {
      width: 160px!important;
    }
}

::v-deep .biz-form-remote-select-clear {
  top: 2px!important;
}

::v-deep .el-input__suffix {
    right: 1px;
  }

.condition-wrap {
  padding: 12px;
  background: #f5f5f5;
}
</style>